package linkvalidator

import (
	"time"
	"yunj/app/enum/linkenum"
	"yunj/app/model"
	"yunj/pkg/yunj/app/enum/stateenum"
	"yunj/pkg/yunj/util"

	"github.com/worklz/go-validate"
)

type Link struct {
	validate.Validator
}

func (v *Link) HandleDatas(datas map[string]interface{}, scene string) (err error) {
	if scene == "FormSubmit" {
		err = v.HandleDatasByFormSubmit(datas)
		if err != nil {
			return
		}
	}
	return
}

func (v *Link) HandleDatasByFormSubmit(datas map[string]interface{}) (err error) {
	currTime := time.Now().In(time.Local)
	dbLink := &model.Link{
		Link: util.MapKeyValue(datas, "link", ""),
		Desc: util.MapKeyValue(datas, "desc", ""),
	}
	// last_update_time
	dbLink.LastUpdateTime = currTime.Unix()
	// status
	if statusRaw, exists := datas["status"]; exists {
		if statusValue, ok := linkenum.StatusEnum.IsValue(statusRaw); ok {
			dbLink.Status = statusValue
		}
	}
	// id
	var id uint64
	if idRaw, exists := datas["id"]; exists {
		var idVal uint64
		if idVal, err = util.ToUint64(idRaw); err == nil && idVal > 0 {
			id = idVal
		}
	}
	if id > 0 {
		// 编辑
		dbLink.Id = id
	} else {
		// 新增
		dbLink.CreateTime = currTime.Unix()
		dbLink.State = stateenum.NORMAL
	}
	datas["dbLink"] = dbLink
	return
}
